package  com.syqc.sensor.recent

import android.content.Intent
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import autodispose2.autoDispose
import com.google.android.material.tabs.TabLayout
import com.gyf.immersionbar.ktx.immersionBar
import com.syqc.adapter.ChooseTimeAdapter
import com.syqc.choose.car.ChooseCarActivity
import com.syqc.choose.teamcar.TeamsCarsActivity
import com.syqc.comlib.base.BaseActivity
import com.syqc.comlib.custom.timer.CustomDatePicker
import com.syqc.comlib.custom.timer.DateFormatUtils
import com.syqc.comlib.utils.ActivityResultUtil.launchAct
import com.syqc.comlib.utils.ActivityResultUtil.registerResultOk
import com.syqc.interfaces.SimpleTabLayoutListener
import com.syqc.monitor.R
import com.syqc.monitor.databinding.ActivityRecentOil2Binding
import com.syqc.monitor.databinding.IncludeTabLayoutBinding
import com.syqc.utils.DataUtil
import com.syqc.utils.Keys
import com.syqc.utils.NetDataUtil
import com.syqc.utils.TimeUtil

class RecentOilActivity :
    BaseActivity<ActivityRecentOil2Binding>(ActivityRecentOil2Binding::inflate) {
    private val mViewModel by viewModels<RecentOilVM>()
    private val mTimeAdapter by lazy { ChooseTimeAdapter() }
    private val mFragments by lazy { ArrayList<Fragment>() }
    private val layoutManager by lazy {
        LinearLayoutManager(
            this,
            LinearLayoutManager.HORIZONTAL,
            false
        )
    }
    private lateinit var mTabVB: IncludeTabLayoutBinding

    //自定义
    private lateinit var time: TextView

    override fun initView() {
        immersionBar { titleBar(binding.llToolbar) }
        mTabVB = IncludeTabLayoutBinding.bind(binding.root)
        initTimeRecycler()
        initData()
        mViewModel.dStart = mViewModel.nowTimeFormat()
        mViewModel.dEnd = mViewModel.nowTimeFormat()
        mViewModel.chooseTime(0)
        initIntent()

    }

    private fun initTimeRecycler() {
        binding.rvTime.layoutManager = layoutManager
        binding.rvTime.adapter = mTimeAdapter

        val view = View.inflate(this, R.layout.choose_time_head, null)
        time = view.findViewById<TextView>(R.id.tvTimeTitle)
        time.setText(R.string.desc_com_define)
        time.setOnClickListener {
            binding.tvStartTime.text = mViewModel.dStart
            binding.tvEndTime.text = mViewModel.dEnd
            mTimeAdapter.index = 0
            binding.llChooseTime.isVisible = true
            time.isSelected = true
            mTimeAdapter.notifyDataSetChanged()
            removeAll()
            mViewModel.isParamOk(mViewModel.dStart, mViewModel.dEnd)
        }
        mTimeAdapter.addHeaderView(view, -1, orientation = LinearLayout.HORIZONTAL)
    }

    override fun setListener() {
        binding.ivBack.setOnClickListener {
            if (isHome) {
                startHomeActivity()
            }
            finish()
        }
        binding.tvChooseCar.setOnClickListener {

            if (NetDataUtil.isSyncTree) {
                launcher.launchAct<TeamsCarsActivity>(this) {
                    putExtra("VideoCar", true)
                }
            } else {
                launcher.launchAct<ChooseCarActivity>(this) {
                    putExtra("VideoCar", true)
                }
            }
        }
        binding.tvToChooseCar.setOnClickListener {
            if (NetDataUtil.isSyncTree) {
                launcher.launchAct<TeamsCarsActivity>(this) {
                    putExtra("VideoCar", true)
                }
            } else {
                launcher.launchAct<ChooseCarActivity>(this) {
                    putExtra("VideoCar", true)
                }
            }
        }

        binding.tvStartTime.setOnClickListener {
            mViewModel.isStart = true
            mDatePicker.show(binding.tvStartTime.text.toString())
        }
        binding.tvEndTime.setOnClickListener {
            mViewModel.isStart = false
            mDatePicker.show(binding.tvEndTime.text.toString())
        }

        mTimeAdapter.setOnItemClickListener { _, _, position ->
            if (position >= 3) {
                // 平滑滚动到指定位置
                layoutManager.scrollToPositionWithOffset(position, 0)
            }
            mTimeAdapter.index = position + 1
            binding.llChooseTime.isVisible = false
            time.isSelected = false
            mTimeAdapter.notifyDataSetChanged()
            mViewModel.chooseTime(position)
            removeAll()
            mViewModel.isParamOk(
                binding.tvStartTime.text.toString(),
                binding.tvEndTime.text.toString()
            )
        }

        mTabVB.tabLayout.addOnTabSelectedListener(object : SimpleTabLayoutListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                showFragment(mFragments[tab?.position ?: 0])
            }
        })
    }

    fun initData() {
        mTimeAdapter.setList(mViewModel.timeList)
        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)
        mViewModel.cfgLiv.observe(this) {
            binding.llChooseCar.isVisible = true
            binding.tvToast.setText(it)

        }
        mViewModel.startObserve().autoDispose(scopeProvider).subscribe {
            binding.tvStartTime.text = it
        }

        mViewModel.endObserve().autoDispose(scopeProvider).subscribe {
            binding.tvEndTime.text = it
        }
        //显示数据
        mViewModel.dataLive.observe(this) {

            it.forEachIndexed { index, statsType ->
                mFragments.add(
                    RecentOilInfoFragment.getInstance(
                        mViewModel.carName,
                        mViewModel.carId,
                        mViewModel.teamName,
                        index
                    )
                )
                mTabVB.tabLayout.addTab(mTabVB.tabLayout.newTab())
                mTabVB.tabLayout.getTabAt(index)?.text = statsType.name
            }
            if (it.size > 0) {
                binding.llChooseCar.isVisible = false
            }
            showFragment(mFragments[0])
            mTabVB.tabLayout.isVisible = (it?.size ?: 0) >= 2
        }

    }

    private val mDatePicker: CustomDatePicker by lazy {
        CustomDatePicker(
            this,
            callback,
            TimeUtil.normalDate,
            mViewModel.nowTimeFormat(),
            !mViewModel.isSimple
        ).apply {
            setCanShowPreciseTime(!mViewModel.isSimple)
        }
    }

    private val callback: CustomDatePicker.Callback = object : CustomDatePicker.Callback {
        override fun onTimeSelected(timestamp: Long) {
            mTimeAdapter.index = -1
            mTimeAdapter.notifyDataSetChanged()
            val time: String = DateFormatUtils.long2Str(timestamp, !mViewModel.isSimple)
            if (mViewModel.isStart) {
                binding.tvStartTime.text = time
                mViewModel.dStart = time
                removeAll()
                mViewModel.isParamOk(time, binding.tvEndTime.text.toString())
            } else {
                binding.tvEndTime.text = time
                mViewModel.dEnd = time
                removeAll()
                mViewModel.isParamOk(binding.tvStartTime.text.toString(), time)
            }
            mDatePicker.dismiss()
        }
    }

    private val launcher = registerResultOk { result ->
        result.data?.let {
            removeAll()
            it.handleCarInfo(true)
        }
    }

    private var currentFragment: Fragment? = null
    private fun showFragment(fragment: Fragment) {
        if (currentFragment != null && currentFragment == fragment) return
        supportFragmentManager.beginTransaction().apply {
            currentFragment?.let { hide(it) }
            currentFragment = fragment
            if (fragment.isAdded) {
                show(fragment)
            } else {
                add(R.id.content, fragment).show(fragment)
            }
        }.commit()
    }


    override fun onDestroy() {
        super.onDestroy()
        removeAll()
        DataUtil.dayStats = null
        currentFragment = null
    }

    /**
     * 移除全部
     *
     */
    fun removeAll() {
        mTabVB.tabLayout.removeAllTabs()
        mFragments.clear()
    }

    //处理调转过来的数据
    private fun initIntent() {
        val carId = intent.getStringExtra(Keys.INTENT_CAR_ID)
        if (carId == null) {

            if (NetDataUtil.isSyncTree) {
                launcher.launchAct<TeamsCarsActivity>(this) {
                    putExtra("VideoCar", true)
                }
            } else {
                launcher.launchAct<ChooseCarActivity>(this) {
                    putExtra("VideoCar", true)
                }
            }
            return
        }
        intent.handleCarInfo()
        binding.tvChooseCar.isEnabled = false
        binding.tvToChooseCar.isVisible = false

    }

    private fun Intent.handleCarInfo(isIntent: Boolean = false) {
        val carId = getStringExtra(Keys.INTENT_CAR_ID) ?: ""
        val carName = if (isIntent) {
            getStringExtra(Keys.INTENT_CAR_NAME) ?: ""
        } else {
            getStringExtra(Keys.INTENT_PLATE) ?: ""
        }
        val teamName = getStringExtra(Keys.INTENT_TEAM_NAME) ?: ""

        mViewModel.carId = carId
        mViewModel.carName = carName
        mViewModel.teamName = teamName
        binding.tvTitle.text = carName
        mViewModel.isParamOk(
            binding.tvStartTime.text.toString(),
            binding.tvEndTime.text.toString()
        )
    }
}

